import { UserService } from "admin/services/user";
import React = require("react");
import ReactDOM = require("react-dom");
import * as chitu from "maishu-chitu";
import site from "admin/site";

export default function (page: chitu.Page) {

    let app = page.app as chitu.Application;
    
    interface State {
        resources: (Resource & { selected?: boolean })[],
        role?: Role
    }

    let service = page.createService(UserService)
    let roleId = page.data.roleId as string
    console.assert(roleId != null);

    class RolePage extends React.Component<any, State>{
        constructor(props) {
            super(props)

            this.state = { resources: null }

        }
        componentDidMount() {
            service.allResources().then(items => {
                this.setState({ resources: items })
            })


            Promise.all([service.getRole(roleId), service.roleResources(roleId), service.allResources()])
                .then(args => {
                    let role = args[0]
                    let roleResources = args[1]
                    let resources = args[2]
                    for (let i = 0; i < roleResources.length; i++) {
                        let resource = resources.filter(o => o.id == roleResources[i].resource_id)[0] as (Resource & { selected?: boolean })
                        if (resource) {
                            resource.selected = true
                        }
                    }
                    this.setState({ role, resources })
                })
        }
        isSelectedAll() {
            let resources = this.state.resources || []
            let selectedChildren = resources.filter(o => o.selected == true)
            let result = selectedChildren.length == resources.length
            return result
        }
        checkAll(isSelect: boolean) {
            let resources = this.state.resources || []
            resources.forEach(item => {
                item.selected = isSelect
            })
            this.setState({ resources })
        }
        isSelectedAllChild(resourceId: string) {
            let resources = this.state.resources || []
            let children = resources.filter(o => o.parent_id == resourceId)
            let selectedChildren = children.filter(o => o.selected == true)
            let result = selectedChildren.length == children.length
            return result
        }
        checkAllChild(resourceId: string, isSelect: boolean) {
            let resources = this.state.resources || []
            resources.filter(o => o.parent_id == resourceId)
                .forEach(o => {
                    o.selected = isSelect
                })
            this.setState({ resources })
        }
        checkItem(resourceId: string, isSelect: boolean) {
            let resources = this.state.resources || []
            let item = resources.filter(o => o.id == resourceId)[0]
            console.assert(item != null);
            item.selected = isSelect
            this.setState({ resources })
        }
        async save() {
            // app.createService()
            let resourceIds = this.state.resources.filter(o => o.selected).map(o => o.id)
            return service.setResources(roleId, resourceIds)
        }
        render() {
            let resources = this.state.resources || []
            let role = this.state.role
            let topResources = resources.filter(o => o.parent_id == null)
            return [
                <ul key={10} className="nav nav-tabs clearfix">
                    <li className="pull-right">
                        <button className="btn btn-primary btn-sm"
                            onClick={() => app.back()}>
                            <i className="icon-reply" />
                            <span>返回</span>
                        </button>
                    </li>
                    <li className="pull-right">
                        <button className="btn btn-primary btn-sm"
                            ref={e => {
                                ui.buttonOnClick(e, () => this.save(), {
                                    toast: '保存成功'
                                })
                            }} >
                            <i className="icon-save" />
                            <span>保存</span>
                        </button>
                    </li>
                </ul>,
                <div key={20} className="well">
                    <div className="row form-group">
                        <label className="col-md-4" style={{ width: label_max_width }}>
                            名称
                    </label>
                        <div className="col-md-8" style={{ maxWidth: input_max_width }}>
                            <input type="text" className="form-control" value={role ? role.name : ''} />
                        </div>
                    </div>
                    <div className="row form-group">
                        <label className="col-md-4" style={{ width: label_max_width }}>
                            备注
                        </label>
                        <div className="col-md-8" style={{ maxWidth: input_max_width }}>
                            <textarea className="form-control" />
                        </div>
                    </div>
                    <div className="row form-group">
                        <label className="col-md-4" style={{ width: label_max_width }}>
                            权限
                        </label>
                        <div className="col-md-8">
                            <div className="list-group">
                                {topResources.map(item => <React.Fragment key={item.id}>
                                    <div className="list-group-item">
                                        <h4 className="list-group-item-heading">
                                            <input type="checkbox" checked={this.isSelectedAllChild(item.id)}
                                                onChange={e => this.checkAllChild(item.id, e.target.checked)} />
                                            <span style={{ paddingLeft: 4 }}>{item.name}</span>
                                        </h4>
                                        <div className="list-group-item-text clearfix">
                                            {resources.filter(o => o.parent_id == item.id).map(child =>
                                                <div key={child.id} className="col-lg-2" style={{ padding: 0, margin: 0, marginTop: 8 }}>
                                                    <div>
                                                        <input type="checkbox" checked={child.selected || false}
                                                            onChange={e => {
                                                                this.checkItem(child.id, e.target.checked)
                                                            }} />
                                                        <span style={{ paddingLeft: 4 }}>{child.name}</span>
                                                    </div>
                                                </div>
                                            )}
                                        </div>
                                    </div>

                                </React.Fragment>
                                )}
                            </div>
                            <label>
                                <input type="checkbox" checked={this.isSelectedAll()}
                                    onChange={e => {
                                        this.checkAll(e.target.checked)
                                    }} /> 全选
                            </label>
                        </div>
                    </div>

                </div>

            ]
        }
    }

    ReactDOM.render(<RolePage />, page.element);
    site.loadCSS(page.name);
}

const label_max_width = 80;
const input_max_width = 300;

// {menuData.filter(o => o.visible != false).map(o => [
//     <div key={o.title} className="row form-group">
//         <label className="col-md-4" style={{ width: label_max_width }} />
//         <label className="col-md-8" style={{ maxWidth: input_max_width }}>
//             <input type="checkbox" />
//             <span>{o.title}</span>
//         </label>
//     </div>,
//     ...o.children.filter(o => o.visible != false).map(o => [
//         <div key={o.title} className="row form-group">
//             <label className="col-md-4" style={{ width: label_max_width }} />
//             <label className="col-md-8 level1" style={{ maxWidth: input_max_width }}>
//                 <input type="checkbox" />
//                 <span>{o.title}</span>
//             </label>
//         </div>,
//         ...o.children.filter(o => o.visible != false).map(o => [
//             <div key={o.title} className="row form-group">
//                 <label className="col-md-4" style={{ width: label_max_width }} />
//                 <label className="col-md-8 level2" style={{ maxWidth: input_max_width }}>
//                     <input type="checkbox" />
//                     <span>{o.title}</span>
//                 </label>
//             </div>,
//         ])
//     ])
// ])}
